from datetime import timezone, timedelta, datetime

import pytz as pytz
import time
from dateutil.parser import parse

null_datetime = datetime(1900, 1, 1, 0, 0, 0)


def tz_str_to_tz(tz_str=None):
    """
    时区字符串 -> pytz时区
    注意：tz_str in pytz.all_timezones == True
    """
    if tz_str:
        return pytz.timezone(tz_str)
    else:
        return pytz.utc


def str_to_datetime(datetime_str):
    """
    字符串格式的时间 -> 时间对象
    `time str` -> `datetime tuple`

    eg:
    "2019-01-18T06:08:00" -> datetime.datetime(2019, 1, 18, 06, 08)
    """
    try:
        datetime_obj = parse(datetime_str)
    except (ValueError, TypeError):
        return None

    return datetime_obj


def datetime_to_str(datetime_obj):
    """
    时间对象 -> 字符串格式的时间(API)

    :return:
    '2019-01-18T06:08:00'
    """
    try:
        datetime_str = datetime_obj.replace(microsecond=0).isoformat()
    except AttributeError:
        return ''

    return datetime_str


def date_to_str(datetime_obj):
    """
    时间对象 -> 字符串格式的时间(API)

    :return:
    '2019-01-18T06:08:00'
    """
    try:
        datetime_str = datetime_obj.isoformat()
    except AttributeError:
        return ''

    return datetime_str


def time_to_str(time_obj):
    """
    时间time对象 -> 字符串格式的时间(API)

    :return:
    '09:40:21'
    """
    try:
        time_str = time_obj.replace(microsecond=0).isoformat()
    except AttributeError:
        return ''

    return time_str


def timeit(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        duration = (time.time() - start_time) * 1000
        print("function %s execute duration is : %f" % (str(func), duration))
        return result

    return wrapper
